<?php


namespace app\api\controller;


use app\service\model\MemberModel;
use app\service\Token;
use app\service\Wechat;
use app\service\Y;
use EasyWeChat\Factory;

class Login extends BaseApi
{

    /**
     * 小程序授权登录
     * @return \think\response\Json
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     * @throws \app\service\exception\ApiException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function mplogin()
    {
        $config = config('wechat.mini_program');
        $app = Factory::miniProgram($config);

        $code = input('param.code', '');
        $encryptedData = input('param.encryptedData', '');
        $iv = input('param.iv', '');
        $wechat_info = input('wechat_info/a', []);

        $res = $app->auth->session($code);
        if (isset($res['openid'])) {
            // 授权成功
            // 解析加密串
            $wechat = new Wechat($config['app_id'], $res['session_key']);
            $wechat->decryptData($encryptedData, $iv, $user_wx_info, $wechat_info);

            // 检查用户是否存在
            $member = MemberModel::where('wx_unionid', '=', $res['unionid'])->find();
            if (!$member) {
                // 创建用户信息
                $member = MemberModel::create([
                    'wx_unionid' => $res['unionid'] ?? '',
                    'xcx_openid' => $res['openid'],
                    'nickname' => $user_wx_info['nickName'],
                    'headimgurl' => $user_wx_info['avatarUrl'],
                ]);
            } else {
                // 更新用户信息
                $member->xcx_openid = $res['openid'];
                $member->nickname = $user_wx_info['nickName'];
                $member->headimgurl = $user_wx_info['avatarUrl'];
                $member->save();
            }

            return Y::success([
                'token' => Token::getMemberToken($member->id)['token'],
                'user_wx_info' => $user_wx_info
            ], '授权成功');
        } else {
            return Y::error('授权失败', $res);
        }
    }
}